package jmine.tec.persist.schema.impl.parsers;

import java.util.regex.Matcher;

import jmine.tec.persist.schema.impl.elements.CheckConstraintElement;
import jmine.tec.persist.schema.impl.elements.Schema;

/**
 * Parser de check constraints
 * 
 * @author lundberg
 */
public class CheckConstraintParser extends AbstractSchemaElementParser<CheckConstraintElement> {

    private static final int TABLE_NAME_GROUP_INDEX = 1;

    private static final int CHECK_NAME_GROUP_INDEX = 2;

    private static final int CONDITION_GROUP_INDEX = 3;

    private static final int COLUMN_GROUP_INDEX = 4;

    /**
     * Construtor
     * 
     * @param schema schema
     */
    public CheckConstraintParser(Schema schema) {
        super("alter\\s+table\\s+(" + TableParser.TABLE_NAME_REGEX + ")\\s+add\\s+constraint\\s+(\\w+)\\s+check\\s+\\(((\\w+).*)\\)",
                schema);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CheckConstraintElement doParse(Matcher matcher) {
        String table = matcher.group(TABLE_NAME_GROUP_INDEX);
        String name = matcher.group(CHECK_NAME_GROUP_INDEX);
        String condition = matcher.group(CONDITION_GROUP_INDEX);
        String column = matcher.group(COLUMN_GROUP_INDEX);
        return new CheckConstraintElement(table, name, condition, this.getSchema().findTable(table).findColumn(column));
    }
}
